import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2023-02-21
 * Time: 21:55
 */
public class MyPriorityQueue {
    public int[] elem;
    public int usedSize;

    public MyPriorityQueue() {
        this.elem = new int[10];
    }
    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    /**
     * 建堆的时间复杂度：O(N)
     *
     * @param array
     */
    public void createHeap(int[] array) {
        int parent = (array.length-1-1) / 2;
        while (parent >= 0) {
            shiftDown(parent, usedSize);
            parent--;
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        //左孩子
        int child = root*2+1;
        while (child < len) {
            if(child +1 < len && elem[child] < elem[child+1]) {
                child = child+1;
            }
            if(elem[child] > elem[root]) {
                int tmp = elem[child];
                elem[child] = elem[root];
                elem[root] = tmp;
                root = child;
                child = root*2+1;
            }else {
                break;
            }
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        elem[usedSize++] = val;
        shiftUp(usedSize-1);
    }

    private void shiftUp(int child) {
        int parent = (child-1) / 2;
        while (child > 0) {
            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1) / 2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        if(isEmpty()) {
            return;
        }
        swap(elem,0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }

    private void swap(int[] array, int n, int m) {
        int tmp = array[n];
        array[n] = array[m];
        array[m] = tmp;
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(isEmpty()) {
            return -1;
        }
        return elem[0];
    }

    public void heapSort() {
        int end = usedSize-1;
        while (end > 0) {
            swap(elem, 0, end);
            shiftDown(0,end);
            end--;
        }
    }
}
